<?php

namespace app\console\controller;



use app\console\model\Service as FeedbackTypeModel;

use think\Request;

use think\Url;

use think\Db;

use think\Controller;

use think\Response;

use think\Loader;



class Service extends Controller

{

    /*

     * 列表

     */

    public function index()

    {

        // 获取参数

        $inquire = Request::instance()->param();

        if(session('auding_status') == 1){

            $where['shop_id'] = ['eq',session('shop_id')];

        }else{

            $where = [];

        }



        // 搜索条件

        if(!empty($inquire['service_date'])) $where['service_date'] = ['eq',$inquire['service_date']];

        if(!empty($inquire['shop_id'])) $where['shop_id'] = ['eq',$inquire['shop_id']];

//        if(!empty($inquire['title'])) $where['shop_id'] = ['eq',$inquire['shop_id']];
		$level = Db::name('manager')->where(['id' => session('manage_id'),])->order('id', 'desc')->value('level');
        $data = FeedbackTypeModel::where($where)->order(['service_date' => 'desc','service_time' => 'asc'])->group('service_date')->paginate(30, false, ['query' => $inquire])->each(function ($item,$key) use ($where){

            $item->count = FeedbackTypeModel::where('service_date',$item->service_date)->count();

            $item->list = FeedbackTypeModel::where($where)->where('service_date',$item->service_date)->order(['station_id' =>'asc','service_time_id' => 'asc'])->select()->each(function ($item2,$key) use ($item){

                $item2->title = Db::name('station')->where('id',$item2->station_id)->value('title');
				$level = Db::name('manager')->where(['id' => session('manage_id'),])->order('id', 'desc')->value('level');
				//$item->status = Db::name('order')->where('id',$item->order_id)->value('status');
				if($level !='1' && $level !='5'){
					$item2['member']['username']  =substr_replace($item2['member']['username'],'*****',2,5);
					$item2['member']['username']=substr_replace($item2['member']['username'],'*****',2,5);
					session('shifou_chaoguan', 1);
					
				}else if($level =='5'){
					//$item2['member']['username']  =substr_replace($item2['member']['username'],'*****',2,5);
					//$item2['member']['username']=substr_replace($item2['member']['username'],'*****',2,5);
					session('shifou_chaoguan', 1);
					//$item2['member']['username']  =substr_replace($item2['member']['username'],'*****',2,5);
					if(!empty($item2['member']['username'])){
						$item2['member']['username']  =substr_replace($item2['member']['username'],'*****',2,5);
					}
					//var_dump($item2['member']['username']);
				}else{
					session('shifou_chaoguan', 2);	
					//$item2['member']['username']  =substr_replace($item2['member']['username'],'*****',2,5);
					//$item2['member']['username']=substr_replace($item2['member']['username'],'*****',2,5);
				}
                //$item2->list2= FeedbackTypeModel::where('service_time',$item2->service_time)->where('service_date',$item2->service_date)->order(['service_time' => 'asc'])->select();
            });
			
			
			
        });
		
        if(session('auding_status') == 1){

            $where2['shop_id'] = ['eq',session('shop_id')];

        }else{

            $where2 = [];

        }

        if(!empty($inquire['shop_id'])) $where2['shop_id'] = ['eq',$inquire['shop_id']];

        $data['count'] = FeedbackTypeModel::where($where2)->count();



        return $this->fetch('index', [

            'mate_title' => '反馈分类列表',

            'data'       => $data

        ]);

    }



    public function tenmin(){

        $ret = Db::name('service')->where('shop_id',session('shop_id'))->where('is_read_shop',1)->find();

        if($ret){ //存在未读提醒

            return true;

        }

        return false;

    }



    public function excel()

    {

        // 获取参数

        $inquire = Request::instance()->param();

        if(session('auding_status') == 1){

            $where['shop_id'] = ['eq',session('shop_id')];

        }else{

            $where = [];

        }



        // 搜索条件

        if(!empty($inquire['service_date'])) $where['service_date'] = ['eq',$inquire['service_date']];

        if(!empty($inquire['shop_id'])) $where['shop_id'] = ['eq',$inquire['shop_id']];

        $data = FeedbackTypeModel::with(['Member','shop'])->where($where)->order(['service_date' => 'desc','service_time' => 'asc'])->select();

       // halt($data->toArray());

        $this->push($data,'预约服务导出');

        return $this->fetch('index', [

            'mate_title' => '反馈分类列表',

            'data'       => $data

        ]);

    }





    /*

     * 添加

     */

    public function create()

    {

        $order_id = Request::instance()->param('order_id');

        if (Request::instance()->isPost()) {

            $data = Request::instance()->param();

            // 验证

            $validate = Loader::validate('FeedbackType');

            //if (!$validate->scene('create')->check($data)) fail($validate->getError());



            // 提交数据

//            halt($data);

            $dispose = (new FeedbackTypeModel())->allowField(true)->save($data);



            if ($dispose) {

                win('操作成功', Url::build('index',Request::instance()->route()));

            }

            fail('操作失败');

        }



        if(empty($order_id)){

            fail('请去礼包详情选择订单');

        }

        $order = (new \app\index\model\Order())->find($order_id);



        return $this->fetch('create', [

            "mate_title" => '反馈分类添加',

            'item' => $order

        ]);



    }



    /*

     * 删除

     */

    public function destroy($id)

    {



        if (FeedbackTypeModel::destroy($id)) {

            win('操作成功', Url::build('index'));

        }



        fail('操作失败');



    }



    /*

     * 编辑

     */

    public function update($id)

    {

        $get = Request::instance()->get();

        (new FeedbackTypeModel())->allowField(true)->save(['is_read_shop' => 2], ['id' => $id]);

        $item = FeedbackTypeModel::get($id);

        if (Request::instance()->isPost()) {



            $data = Request::instance()->param();

            $data2 = Request::instance()->route();



            // 验证

            $validate = Loader::validate('FeedbackType');

           // if (!$validate->scene('create')->check($data)) fail($validate->getError());

            if($item['status'] == 1){

                $data['status'] =2;

                $data['arrive_time'] = date('Y-m-d H:i:s');

            }

            if($item['status'] == 2){

                $data['status'] =3;

                $data['finish_time'] = date('Y-m-d H:i:s');

            }





            // 提交数据

            $dispose = (new FeedbackTypeModel())->allowField(true)->save($data, ['id' => $id]);



            if ($dispose !== false) {

                win('操作成功', Url::build('index',$data2));

            }



            fail('操作失败');



        }



        $item = FeedbackTypeModel::get($id);



        $order_id = Request::instance()->param('order_id');

        $order = (new \app\index\model\Order())->find($order_id);



        return $this->fetch('create', [

            "mate_title" => '反馈分类编辑',

            'item2'       => $item,

            'item' => $order



        ]);

    }



    /*

     * 启用状态改变

     */

    public function status()

    {

        $id = Request::instance()->param('id');

        $find = FeedbackTypeModel::where('id', $id)->find();

        $status = FeedbackTypeModel::where('id', $id)->value('stop_order') == '1' ? 2 : 1;

        if (FeedbackTypeModel::where('shop_id', $find['shop_id'])->where('service_date',$find['service_date'])->where('service_time',$find['service_time'])->update(['stop_order' => $status])) {

            return $status;

        }

        return false;

    }



    /*

     * 排列顺序

     */

    public function sorting()

    {



        $id = Request::instance()->param('orderId/a');

        $sort = Request::instance()->param('sort/a');



        foreach ($id as $key => $value) {

            FeedbackTypeModel::where('id', $value)->update(['sort' => $sort[$key]]);

        }



        win('操作成功', Url::build('FeedbackType/index'));

    }



    public function push($data, $name = 'Excel')

    {



        set_time_limit(0);



        ini_set('memory_limit', '1024M');



        error_reporting(E_ALL);



        date_default_timezone_set('Asia/Shanghai');







        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');



        $objPHPExcel = new \PHPExcel();







        /*以下是一些设置 ，什么作者  标题啊之类的*/



        $objPHPExcel->getProperties()->setCreator("管理员")



            ->setLastModifiedBy("管理员")



            ->setTitle("电话本导出")



            ->setSubject("数据EXCEL导出")



            ->setDescription("备份数据")



            ->setKeywords("excel")



            ->setCategory("result file");



        $objPHPExcel->setActiveSheetIndex(0)



            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推



            ->setCellValue('A1', 'ID')

            ->setCellValue('B1', '预约日期')

            ->setCellValue('C1', '预约时间')

            ->setCellValue('D1', '预约用户')

            ->setCellValue('E1', '预约服务')

            ->setCellValue('F1', '服务状态')

            ->setCellValue('G1', '门店名称')

            ->setCellValue('H1', '创建日期')



        ;

        $sheet1 = [];

        for ($x = 0; $x < count($sheet1); $x++) {

            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(

                array(



                    'font'      => array(



                        'bold' => true



                    ),



                    'alignment' => array(



                        'horizontal' =>



                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER



                    )



                )



            );



        }



        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/



        $n = 0;



        foreach ($data as $v) {



            $num = $n + 2;

            $objPHPExcel->setActiveSheetIndex(0)



                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推

                ->setCellValue('A' . $num, $v['id'])

                ->setCellValue('B' . $num, $v['service_date'])

                ->setCellValue('C' . $num, $v['service_time'])

                ->setCellValue('D' . $num, "\t".$v['member']['username']."\t")

                ->setCellValue('E' . $num, $v['single']['cat_name'])

                ->setCellValue('F' . $num, $v['statusa'])

                ->setCellValue('G' . $num, $v['shop']['shop_title'])

                ->setCellValue('H' . $num, $v['create_time'])





            ;



            $n++;



        }







        $objPHPExcel->getActiveSheet(0)->setTitle('订单信息导出');

        $objPHPExcel->setActiveSheetIndex(0);







        ob_end_clean();



        header('Content-Type: application/vnd.ms-excel');



        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');



        header('Cache-Control: max-age=0');



        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');



        $objWriter->save('php://output');

        exit;

    }

}

